var base_info = require('/base_info.js');
var extJson = my.getExtConfigSync();

// 封装请求
exports.getData = function (url, data, successCallback, failCallback) {
  let params = {
    i: base_info.i,
    a: base_info.a,
    c: base_info.c,
    m: base_info.m,
    do: url,
    version: extJson.version,
    shopid: extJson.shopId,
    minishopid: extJson.miniShopId, 
    appid: extJson.appId
  };
  data = Object.assign(data, params);
  my.httpRequest({
    url: base_info.baseurl,
    method: 'GET',
    data: data,
    headers: {
      shopid: extJson.shopId,
      minishopid: extJson.miniShopId,
      appid: extJson.appId
    },
    dataType: 'json',
    success: function(res) {
      my.hideLoading();
      if (res.data.errno == 1) {
        successCallback(res); 
      } else {
        my.alert({
          title: `${res.data.message}`
        });
      };
    },
    fail: function(res) {
      my.hideLoading();
      my.alert({
        title: `网络错误，请稍后再试[错误代码：${url}]`
      });
    }
  });
}

// 获取用户信息
exports.getAuthCode = function (callback) {
  let that = this;
  my.getAuthCode({
    scopes: 'auth_user',
    success: (res) => {
      // 换取用户隐私数据 
      that.getData('AliUserInfo', {
        auth_code: res.authCode,
        type: 1
      }, (res) => {
        console.log(res.data.data);
        // 保存用户id
        my.setStorageSync({
          key: 'user_id', // 缓存数据的key   
          data: res.data.data.list.user_id // 要缓存的数据 
        });
        my.setStorageSync({
          key: 'uid', // 缓存数据的key  
          data: res.data.data.uid // 要缓存的数据 
        });
        my.setStorageSync({
          key: 'phone', // 缓存数据的key  
          data: res.data.data.phone // 要缓存的数据 
        });
        my.setStorageSync({
          key: 'user_name', // 缓存数据的key  
          data: res.data.data.list.user_name // 要缓存的数据 
        });
        my.setStorageSync({
          key: 'user', // 缓存数据的key
          data: JSON.stringify(res.data.data), // 要缓存的数据
        });
        callback(res);
      }, (err) => {
        my.navigateBack({});
      });
    },
  });
}